package com.qf.commons.web.exception;

import com.qf.commons.domain.base.Codes;
import com.qf.commons.domain.base.R;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {

    /**
     * 处理全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R globalExceptionHandler(Exception e){
        //打印异常
        log.error("全局异常处理！", e);
        return R.fail(Codes.FAIL);
    }


    /**
     * 处理自定义的异常
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public R serviceExceptionHandler(ServiceException e){
        return R.fail(e.getCodes());
    }

    /**
     * 方法实体的参数校验异常
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R paramsBindExcepiton(MethodArgumentNotValidException e){
        List<String> errorList = e.getBindingResult().getAllErrors()
                .stream()
                //转换方法
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        return R.fail(Codes.PARAMS_BIND, errorList);
    }

    /**
     * 方法形参的参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R paramsBindException(ConstraintViolationException e){
        List<String> result = e.getConstraintViolations().stream()
                .map(constraintViolation -> constraintViolation.getMessage())
                .collect(Collectors.toList());
        return R.fail(Codes.PARAMS_BIND, result);
    }
}
